package com.student.grade.controller;

import com.student.common.entity.Result;
import com.student.common.entity.Grade;
import com.student.grade.service.GradeService;
import com.student.grade.dto.GradeDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;

/**
 * 成绩控制器
 * 
 * @author student
 * @date 2025
 */
@RestController
@RequestMapping("/grade")
public class GradeController {
    
    @Autowired
    private GradeService gradeService;
    
    /**
     * 录入成绩
     */
    @PostMapping
    public Result<String> inputGrade(@RequestBody Grade grade) {
        try {
            boolean success = gradeService.inputGrade(grade);
            if (success) {
                return Result.success("录入成绩成功");
            } else {
                return Result.error("录入成绩失败，可能已存在该成绩记录或教师无权限录入该课程成绩");
            }
        } catch (Exception e) {
            return Result.error("录入成绩失败：" + e.getMessage());
        }
    }
    
    /**
     * 修改成绩
     */
    @PutMapping("/{id}")
    public Result<String> updateGrade(@PathVariable Long id, @RequestBody Grade grade) {
        try {
            grade.setGradeId(id);
            boolean success = gradeService.updateGrade(grade);
            if (success) {
                return Result.success("修改成绩成功");
            } else {
                return Result.error("修改成绩失败，成绩记录不存在或教师无权限修改该课程成绩");
            }
        } catch (Exception e) {
            return Result.error("修改成绩失败：" + e.getMessage());
        }
    }
    
    /**
     * 查询学生成绩
     */
    @GetMapping("/student/{studentId}")
    public Result<Page<Grade>> getStudentGrades(
            @PathVariable String studentId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String semester,
            HttpServletRequest request) {
        try {
            // 获取当前用户信息
            String role = (String) request.getAttribute("role");
            String relatedId = (String) request.getAttribute("relatedId");
            
            // 学生角色只能查询自己的成绩
            if ("学生".equals(role) || "STUDENT".equals(role)) {
                if (!studentId.equals(relatedId)) {
                    return Result.error("权限不足，只能查询自己的成绩");
                }
            }
            
            Pageable pageable = PageRequest.of(page, size);
            Page<Grade> grades = gradeService.getStudentGrades(studentId, semester, pageable);
            return Result.success(grades);
        } catch (Exception e) {
            return Result.error("查询学生成绩失败：" + e.getMessage());
        }
    }
    
    /**
     * 查询课程成绩
     */
    @GetMapping("/course/{courseId}")
    public Result<Page<Grade>> getCourseGrades(
            @PathVariable String courseId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String semester) {
        try {
            Pageable pageable = PageRequest.of(page, size);
            Page<Grade> grades = gradeService.getCourseGrades(courseId, semester, pageable);
            return Result.success(grades);
        } catch (Exception e) {
            return Result.error("查询课程成绩失败：" + e.getMessage());
        }
    }
    
    /**
     * 成绩统计
     */
    @GetMapping("/statistics")
    public Result<Object> getGradeStatistics(@RequestParam(required = false) String semester) {
        try {
            Object statistics = gradeService.getGradeStatistics(semester);
            return Result.success(statistics);
        } catch (Exception e) {
            return Result.error("获取成绩统计失败：" + e.getMessage());
        }
    }
    
    /**
     * 成绩列表查询
     */
    @GetMapping("/list")
    public Result<Page<GradeDTO>> getGradeList(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String studentId,
            @RequestParam(required = false) String courseId,
            @RequestParam(required = false) String semester,
            @RequestParam(required = false) String gradeType,
            HttpServletRequest request) {
        try {
            // 获取当前用户信息
            String role = (String) request.getAttribute("role");
            String relatedId = (String) request.getAttribute("relatedId");
            
            System.out.println("成绩列表查询 - 角色: " + role + ", 关联ID: " + relatedId + ", 原始学号参数: " + studentId);
            
            // 学生角色只能查看自己的成绩列表
            if ("学生".equals(role) || "STUDENT".equals(role)) {
                studentId = relatedId; // 强制设置为当前学生的学号
                System.out.println("学生角色权限控制 - 强制设置学号: " + studentId);
            }
            
            System.out.println("最终查询参数 - 学号: " + studentId + ", 课程: " + courseId + ", 学期: " + semester + ", 成绩类型: " + gradeType);
            
            Pageable pageable = PageRequest.of(page, size);
            Page<GradeDTO> grades = gradeService.getGradeListWithDetails(pageable, studentId, courseId, semester, gradeType);
            
            System.out.println("查询结果 - 总记录数: " + grades.getTotalElements() + ", 当前页记录数: " + grades.getContent().size());
            
            return Result.success(grades);
        } catch (Exception e) {
            System.err.println("查询成绩列表异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("查询成绩列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询成绩
     */
    @GetMapping("/{id}")
    public Result<Grade> getGradeById(@PathVariable Long id) {
        try {
            Grade grade = gradeService.getGradeById(id);
            if (grade != null) {
                return Result.success(grade);
            } else {
                return Result.error("成绩记录不存在");
            }
        } catch (Exception e) {
            return Result.error("查询成绩失败：" + e.getMessage());
        }
    }
}
